package com.gientech.consulconsumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

@RestController
public class ConsumerController {
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("consumer-test")
    public String test(){
        //通过consumer去访问provider
        String rst = restTemplate.getForObject("http://localhost:8001", String.class);

        return "consumer" + rst;
    }

    @Autowired
    DiscoveryClient discoveryClient;
    @RequestMapping("consumer-test1")
    public String test1(){
        List<ServiceInstance> instances = this.discoveryClient.getInstances("provider");
        ServiceInstance serviceInstance = instances.get(0);
        URI uri = serviceInstance.getUri();
        //拿到地址和端口然后做一个拼接
        String targetUrl = uri + "/pro-test";
        String rst = restTemplate.getForObject(targetUrl, String.class);
        return "consumer: " + rst;
    }
}
